package com.mentalhealth.diary.interceptor;

import com.mentalhealth.diary.common.R;
import com.mentalhealth.diary.utils.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * JWT认证拦截器
 * 用于验证请求中的JWT令牌
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取Authorization信息
        String authHeader = request.getHeader("Authorization");
        
        // 跳过OPTIONS请求（预检请求）
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }
        
        // 检查Authorization头是否存在且格式正确
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            // 返回未授权错误
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(new ObjectMapper().writeValueAsString(R.error(401, "未授权，请登录")));
            writer.flush();
            writer.close();
            return false;
        }
        
        // 提取JWT令牌
        String token = authHeader.substring(7);
        
        // 验证JWT令牌
        if (!jwtUtils.validateToken(token)) {
            // 返回令牌无效错误
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(new ObjectMapper().writeValueAsString(R.error(401, "令牌无效或已过期")));
            writer.flush();
            writer.close();
            return false;
        }
        
        // 从令牌中获取用户信息并存储到请求中，供后续使用
        Long userId = jwtUtils.getUserIdFromToken(token);
        String phone = jwtUtils.getPhoneFromToken(token);
        
        request.setAttribute("userId", userId);
        request.setAttribute("phone", phone);
        
        return true;
    }
}